利用html和JavaScript实现加减乘除
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>计算器</title>
<!--javascript部分-->
<script type="text/javascript">
function calc() {
var oper1=document.getElementById("num1");//获取输入数据1
var oper2=document.getElementById("num2");//获取输入数据2
var o=document.getElementById("operator");//获取下拉了列表
var op=o.options[o.selectedIndex].value;//在下拉列表中选中选择的值
var res;
//根据选项进行加减乘除运算
switch (op) {
case " ":
res=change(oper1.value) change(oper2.value);
break;
case "-":
res=change(oper1.value)-change(oper2.value);
break;
case "*":
res=change(oper1.value)*change(oper2.value);
break;
case "/":
res=change(oper1.value)/change(oper2.value);
break;
}
document.getElementById("anw").value=res;//将运算结果赋值到所设置好的anw文本框中
}
//因为在文本框中获取的数据是文本格式要转换成数字格式,利用自带函数paseFloat
function change(x) {
return parseFloat(x);
}
</script>
<!--HTML部分-->
</head>
<body>
<form action="">
<input type="text" id="num1" placeholder="数据1">
<select id="operator">
<option value=" "> </option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>
<input type="text" id="num2" placeholder="数据2">
=
<input type="text" placeholder="答案" id="anw">
<input type="button" value="计算" onclick="calc()">
</form>
</body>
</html>
评论